<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://apps.bdimg.com/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>

<p>Upload File: <input id="fileId" type="file" name="file" /></p>
<canvas id="canvas">Your Broswer don't support html5 canvas</canvas>
<hr>
测试base64图片:<br>
<img alt="" id="img_test" src=""> 

<script>
$(document).ready(function(){
    $("#fileId").change(function(){
        var file = this.files[0];
        var url = webkitURL.createObjectURL(file);//获取文件的url
        var $img = new Image();
        $img.onload = function() {
            //生成比例
            var width = $img.width,
            height = $img.height,
            scale = width / height;
            // width = parseInt(800);
            // width = parseInt(width);
            height = parseInt(width / scale);
            //生成canvas
            var $canvas = $('#canvas');
            // alert($canvas[0]);
            var ctx = $canvas[0].getContext('2d');
            $canvas.attr({width : width, height : height});
            ctx.drawImage($img, 0, 0, width, height);
            var base64 = $canvas[0].toDataURL('image/jpeg',0.3);//压缩过的base64编码形式图片
            // png 会放大图片体积，jpeg 会缩小体积
            // alert(base64);
            // alert(base64.length);//获取字符串比FileReader的短
            
            var img_test = $("#img_test");
            img_test.attr("src",base64);
        }
        $img.src = url;//指定Image的路径（$img.src="common/imgs/add-97617_640.png"）

    });
});

</script>
</body>
</html>
